// JavaScript Document
$(document).ready(function() {
    var fileArray = new Array();
	var showIndex = new Array();
	var num = 0;
    var j_bt_sub = $('#submitForm'),
    j_form = $('#form'),
    j_state = $('#upState'),
    j_file = $('#files');
    var is_support = true;
    if (typeof FileReader === 'undefined') is_support = false;
	
	$("#selectImage").click(function(){
		$('#files').click();
	});
	
	function updateFile(file, k) {
		var reader = new FileReader();
		reader.readAsDataURL(file); (function(k) {
			reader.onloadend = function(e) {
				if (reader.error) {
					alert(reader.error);
				} else {
					var up = $('<div class="image_upload" id="up_' + k + '"></div>');
					var img = $('<img src="' + this.result + '" alt="" id="img_' + k + '">');
					var rate = $('<div class="rate" id="rate_' + k + '">0%</div>');
					var del = $('<div class="delete" title="删除" id="del_' + k + '"></div>');
					up.append(img);
					up.append(rate);
					up.append(del);
					del.click(function() {
						var no = parseInt( $(this).parent()[0].id.substring(3) );
						var k  = showIndex[no];
						showIndex[no] = -1;
						for(var i=no+1; i<showIndex.length; i++)
							showIndex[i]--;
						fileArray.remove(k);
						$(this).parent().remove();
					});
					j_state.append(up);
				}
			};
		})(k);
	}

    j_file.change(function() {
		/*	当重新选择文件时，判断文件是否被选择过。如果文件被选择过，
			那么就忽略。如果是新文件，那么就需要读取文件并创建节点。
		*/
        var fileList = j_file.get(0).files;
		var len = fileArray.length;
		
		for( var i=0; i<fileList.length; i++ )
		{
			var j=0;
			for(; j<len; j++ )
				if( fileList[i].name.localeCompare( fileArray[j].name ) == 0
				&&	fileList[i].size == fileArray[j].size )
					break;
			
			if( j == len )
			{
				fileArray.push(fileList[i]);
				showIndex[num] = fileArray.length - 1;
				updateFile(fileList[i], num++);
			}
		}
    });

    //此处应该支持平滑后退，后面考虑
    j_bt_sub.click(function(e) {
		for (var k = 0, len = showIndex.length; k < len; k++) if( showIndex[k] >= 0 ){
			var file = fileArray[ showIndex[k] ];
			upload(file, k);
		}
    });

    function upload(file, k) {

        var up = $('#up_' + k);
        var img = $('#img_' + k);
        var rate = $('#rate_' + k);
        var del = $('#del_' + k);

        var fd = new FormData();
        fd.append('upload', file);
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress',
        function(e) {
            var percentComplete = Math.round((e.loaded) * 100 / e.total);
            rate.html(percentComplete.toString() + '%');
        }, false);
        
		xhr.onreadystatechange = function(e) {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    rate.html('100%');
                    if (xhr.responseText == "ok") {
						rate.html("上传成功~");
						setTimeout(function() {
							var index = showIndex[k];
							showIndex[k] = -1;
							for(var i=k+1; i<showIndex.length; i++)
								showIndex[i]--;
							fileArray.remove(index);
							$('#up_'+k).fadeOut('slow',function(){
								$('#up_'+k).remove();
							});
						},1000);
					}
                    else {
						rate.html("<font color='red'>上传失败！</font>");
					}
                }
            }
        };
        xhr.open("POST", "?a=processupload");
        xhr.send(fd);
    }

});